﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.Xna.Framework;
using System.Runtime.Serialization;
using StreetlightGames.XnaEngine;

namespace StreetlightGames.SpaceShooter.Patterns
{
    [DataContract]
    public class FlyInCircle : Pattern
    {
        private float _angle;
        private float _startHeading;

        /// <summary>Gets or sets the Radius value</summary>
        [DataMember]
        public float Radius
        {
            get { return _radius; }
            set { _radius = value; }
        }
        private float _radius;

        /// <summary>Gets or sets the Direction value</summary>
        [DataMember]
        public float Direction
        {
            get { return _direction; }
            set { _direction = value; }
        }
        private float _direction;

        /// <summary>Gets or sets the TotalAngle value</summary>
        [DataMember]
        public float TotalAngle
        {
            get { return _totalAngle; }
            set { _totalAngle = value; }
        }
        private float _totalAngle;
        
        public FlyInCircle()
        {
        }

        public FlyInCircle(float radius, float direction, float totalAngle)
        {
            Radius = radius;
            Direction = direction;
            TotalAngle = totalAngle;
        }

        public override void Start()
        {
            _angle = 0;
            _startHeading = Ship.Heading;
            base.Start();
        }

        public override void Update(GameTime gameTime)
        {
            Vector3 acceleration = VectorHelper.RotateY(Ship.Velocity, Direction * MathHelper.PiOver2);
            acceleration.Normalize();
            acceleration *= Ship.Speed * Ship.Speed / Radius;
            float elapsedTime = (float)gameTime.ElapsedGameTime.TotalSeconds;
            float deltaAngle = (float)Math.Abs(Math.Atan2((double)(Ship.Speed) * gameTime.ElapsedGameTime.TotalSeconds, (double)Radius));
            _angle += deltaAngle;
            Ship.Velocity += acceleration * elapsedTime;
            if (Math.Abs(_angle) >= TotalAngle)
            {
                Ship.Heading = _startHeading + TotalAngle * Direction;
                MoveToNextPattern(gameTime);
            }
        }

        public override string ToString()
        {
            return string.Format("Fly In Circle: Direction:{0},Radius:{1:0.0},TotalAngle:{2:0}", Direction, Radius, MathHelper.ToDegrees(TotalAngle));
        }
    }
}
